#!/usr/bin/python
#coding:utf-8

# Copyright 2011 Nicolau Leal Werneck, Anna Helena Reali Costa and
# Universidade de São Paulo
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


###############################################################################
## Trifocal 2D camera location estimation from coplanar points. The
## input to this program are files produced by extract_edgels.



from __future__ import print_function
import sys
import time
import matplotlib
#matplotlib.use('Agg') 
from pylab import *
import scipy.io
import scipy.interpolate

from numpy import dot
from scipy.optimize import fmin
from camori import EdgelSet, PicturePinhole, quaternion_to_matrix, measure_error, quaternion_product, dir_colors

import simplejson

import Image

set_printoptions(precision=3)



if __name__ == '__main__':

    ## Plot stuff immediately
    ion()

    rc('text',usetex=False)

    ## Avoid zero divide warnins...
    np.seterr(divide='ignore')

    #PlotStuff=False
    PlotStuff=True

    #################################################################
    ## Load image and initialize pic object

    ## Sets filename from input argument
    if len(sys.argv) < 2:
        print(sys.argv[0], '<job_file.json>')
        raise Exception('Insufficient number of parameters')

    finput = open(sys.argv[1])
    job_params = simplejson.load(finput)
    finput.close()

    fileroot = job_params['root_directory']

    aa = np.load(fileroot +'/MahaROC.npz', 'w')
    pcdf = aa['pcdf']
    ncdf = aa['ncdf']

    x = 10**mgrid[-2:4.0:0.01]

    dif = pcdf - ncdf

    Li = find(dif==max(dif))[0]
    L = x[Li]
    #print(Li)
    print('Threshold: ', x[Li])
    print('Threshold**2: ', x[Li]**2)
    print('P lik: ', pcdf[Li])
    print('N lik: ', ncdf[Li])

    print('Area under ROC:', scipy.integrate.trapz(pcdf,ncdf))

    for k in range(6):
        aa = np.load(fileroot +'/RgbROC%d.npz'%k, 'w')
        xpcdf = aa['pcdf']
        xncdf = aa['ncdf']
        print('--Individual AUROC%d:'%k, scipy.integrate.trapz(xpcdf,xncdf))
        


    figure(1)
    semilogx(x, pcdf)
    semilogx(x, ncdf)
    semilogx(x, dif)

    semilogx([L,L],[0,1], 'k--')

    figure(2)
    plot(ncdf, pcdf)

    plot(ncdf[Li], pcdf[Li], 'gx', mew=2, ms=10)

    axis('equal')
    grid()

